﻿#include"XQFileTableWidget.h"
#include"XMD5.h"
#include<QFileInfo>
#include<QDesktopServices>
#include<QFileSystemWatcher>
#include<QUrl>
#include<QDir>
#include<QHeaderView>
#include<QMenu>
void XQFileTableWidget::menuInit()
{
	m_menu = new QMenu(this);
	m_menu->setFont(QFont("黑体", 15));
}
void XQFileTableWidget::WatcherInit()
{
	m_Watcher = new QFileSystemWatcher(this);
	connect(m_Watcher, &QFileSystemWatcher::directoryChanged, [this](const QString& path)
		{
			if (path == m_DirPath)
			fileChange();//表格改变
		});
}

void XQFileTableWidget::tableFileInit()
{
	if (m_DirPath.isEmpty())
		return;
	clearContents();
	QDir dir(m_DirPath);
	auto listInfo = dir.entryInfoList(m_nameFilters, QDir::Files, QDir::Name);
	for (auto& info : listInfo)
	{
		auto fileName = info.fileName();
		QString md5 = XMD5::file(info.filePath().toLocal8Bit().toStdString()).c_str();
		m_localFile[fileName] = fileInfo{ fileName,info.filePath(),md5,(size_t)info.size() };
		this->insertLocalFileToTable(m_localFile[fileName]);
	}
	// SetColumnWidth(1);//设置文件名列宽
	SetColumnWidth(Type::size);//设置文件大小列宽
	// 刷新表格
	viewport()->update();
	emit tableFileChange();
}
void XQFileTableWidget::init()
{
	// 启用排序
	this->setSortingEnabled(true);
	UIInit();
	tableFileInit();//初始化表格
	WatcherInit();
	menuInit();
	//双击重命名更改文件名字时
	connect(this, &QTableWidget::cellChanged, [this](int row, int column) {
		if (column != Type::name)
		return;
	auto item = this->item(row, column);//获取当前单元格
	if(isLocalFile(row))
		renamelocalFile(item);
	if (isRemoteFile(row))
		renameremoteFile(item);
		});
	//双击打开文件
	connect(this, &QTableWidget::cellDoubleClicked, this, [this](int row, int column) {
		if (column != Type::name)
		this->openFile();
		});
	//单机标题栏排序
	connect(horizontalHeader(), &QHeaderView::sectionClicked, [this](int index) {
		if (index == 0||rowCount()==0)//单机图标的话跳过,没有数据的时候也跳过
		return;
	sortByColumn(index, (Qt::SortOrder)m_sorts[index]);
	m_sorts[index] = !m_sorts[index];
		});
}